<template>
  <router-view class="nv" v-if="lo" v-bind="{
    match,
    getm,
    time,
    matchuser,
    start,
    isnot,
    result,
    setresult,
    sub,
    statematch,
    setduration
  }"></router-view>
</template>

<script setup lang="ts">
import { Activity } from "../../../admin/views/data";
import {
  Apimatchuserquestion,
  asyncgetactivity,
  asyncgetactivityduration,
  asyncgetactivityuser,
  asyncselectmatchuserquestion,
} from "../../../api";
import { Storekey } from "../../../interface";
import { ElMessage } from "element-plus";

import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { Socket } from "socket.io-client";

import { once } from "underscore";
import {
  computed,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { useStore } from "vuex";
import { useNow } from "@vueuse/core";

const p = defineProps<{ ID: number }>()

const usercount = ref(0)


const id = computed(() => p.ID);
const store = useStore(Storekey);
const lo = ref(false);
const router = useRouter();
const match = reactive<Studycodemodel.Iactivity>(
  Object.assign({}, Activity)
);
const statematch = ref<"开始" | "结束">();
const result = ref<Studycodemodel.Imatchuserquestion[]>();
function setresult(data: Studycodemodel.Imatchuserquestion[]) {
  result.value = data;
}
// 强制提交
const sub = ref(false);

const datenow = computed(() => {
  return store.state.time
})

onBeforeRouteLeave(() => {
  const nav = document.getElementById("nav");
  if (nav) {
    nav.style.display = "none";
  }
});

onBeforeRouteLeave(() => {
  const nav = document.getElementById("nav");
  if (nav) {
    nav.style.display = "block";
  }
});

const timeover = once(() => {
  ElMessage.warning("距离结束还有2分钟");
});
const timeover2 = once(() => {
  ElMessage.warning("距离结束还有10秒, 为您自动提交");
  sub.value = true;
});

const isnot = computed(() => {
  const { activitystarttime, activityendtime } = toRefs(match);
  const start = activitystarttime?.value;
  const stop = activityendtime?.value;
  // 如果比赛没有开始
  if (datenow.value < new Date(start ? start : "").getTime()) {
    return {
      err: 4,
      msg: "比赛还没有开始",
    };
  }

  // 如果比赛已结束
  if (datenow.value > new Date(stop ? stop : "").getTime()) {
    return {
      err: 5,
      msg: "比赛已结束",
    };
  }

  const u: Studycodemodel.Iuser = store.getters.getuser;
  if (!u) {
    return {
      err: 1,
      msg: "没有登录，请登录",
    };
  }
  if (u) {
    const my = match.activityuser?.find((v) => v.userid == u.ID);

    if (!my) {
      if (match.teamid) {
        const team = store.state.team?.rows.find(e => e.ID === match.teamid)
        if (!team) {
          return {
            err: 3,
            msg: "你没有报名，请先报名",
          };
        }
      } else {
        return {
          err: 3,
          msg: "你没有报名，请先报名",
        };
      }
    }
    if (match.format === 'OI') {
      const t = matchuser.value?.userquestion.find((v) => v.userid == u.ID);
      if (t) {
        return {
          err: 2,
          msg: "你已经参加了比赛",
        };
      }
    }
  }
  return {
    err: 0,
    msg: "",
  };
});
const matchuser = ref<Apimatchuserquestion>();
const time = reactive({
  isok: false,
  d: 0,
  h: 0,
  m: 0,
  s: 0,
});
onMounted(() => {
  const nav = document.getElementById("nav");
  if (nav) {
    nav.style.display = "none";
  }
  const socket: Socket | undefined =
    store.state.socket;
  if (socket) {
    socket.on(
      "match",
      (body: {
        error: number;
        msg: string;
        data?: { state: "开始" | "结束" };
      }) => {
        const { error, msg, data } = body;
        if (error) {
          ElMessage.error(msg);
        }
        if (data) {
          statematch.value = data.state;
        }
      }
    );
    socket.on('key', body => {
      getuserquestion()
    })



    if (id.value) {
      socket.emit('matchroom', { activityid: id.value, com: true })
      socket.on('matchroom-length', (body) => {
        usercount.value = body.length
      })
    }
    socket.on('updateactivity', () => {
      start()
    })
  }
  start();
});


onDeactivated(() => {
  if (store.state.socket) {
    store.state.socket.emit('matchroom', { activityid: id.value, com: false })
  }
})

watch(() => store.state.team?.rows, () => {
  if (match.teamid) {
    const team = store.state.team?.rows.find(e => e.ID === match.teamid)
    if (team) {
      match.activityuser?.push({
        userid: store.state.user?.ID,
        activityid: match.ID
      })
    }
  }
})

async function start() {
  if (id.value) {
    await store.dispatch("actiononline");
    const e = await asyncgetactivity({ ID: id.value });
    Object.assign(match, e);
    match.activityuser = []
    lo.value = true;
    if (store.getters.getuser) {
      try {
        const activityuser = await asyncgetactivityuser({
          activityid: id.value,
        })
        match.activityuser = [activityuser]
      } catch (e) {

      }
      await getuserquestion()

      if (match.teamid) {
        const team = store.state.team?.rows.find(e => e.ID === match.teamid)
        if (team) {
          match.activityuser.push({
            userid: store.state.user?.ID,
            activityid: match.ID
          })
        }
      }
      try {
        // 获取比赛时长
        duration.value = await asyncgetactivityduration({ activityid: match.ID })
      } catch (e) {

      }
      if (match.format === 'OI') {
        console.log(matchuser.value)
        if (matchuser.value?.userquestion.length) {
          router.push({
            name: "比赛结束",
          });
        }
      }
    }
  }
}
const duration = ref<{ activityendtime: Date, activitystarttime: Date }>()

async function getuserquestion() {
  matchuser.value = await asyncselectmatchuserquestion({
    ID: id.value,
    my: true,
  });
}

function setduration(data: { activityendtime: Date, activitystarttime: Date }) {
  duration.value = data
}

function getm(s: string, e: string) {
  const c = new Date(s).getTime();
  const d = new Date(e).getTime();
  const x = Math.floor((d - c) / 1000 / 60);
  return x;
}
const timea = window.setInterval(() => {
  const d = datenow.value;

  let f = datenow.value - 1;
  const activityendtime = duration.value ? duration.value.activityendtime : match.activityendtime
  if (activityendtime) {
    f = new Date(activityendtime).getTime();
  } else {
    time.isok = false;
  }
  if (d > f) {
    time.isok = false;
  } else {
    const w2 = 1000 * 60 * 2 + 5000;
    const w3 = 1000 * 10;
    const z = f - d;
    if (z < w2) {
      timeover();
    }
    if (z < w3) {
      timeover2();
    }
    time.isok = true;
    time.d = Math.floor(z / (1000 * 60 * 60 * 24));
    time.h = Math.floor(
      (z - time.d * 1000 * 60 * 60 * 24) / (1000 * 60 * 60)
    );
    time.m = Math.floor(
      (z - time.d * 1000 * 60 * 60 * 24 - time.h * 1000 * 60 * 60) /
      (1000 * 60)
    );
    time.s = Math.floor(
      (z -
        time.d * 1000 * 60 * 60 * 24 -
        time.h * 1000 * 60 * 60 -
        time.m * 1000 * 60) /
      1000
    );
  }
}, 1000);
onBeforeUnmount(() => {
  clearInterval(timea);
});

</script>

<style scoped>
.nv {
  height: 100vh;
  overflow: hidden;
  margin-bottom: 0;
}
</style>
